package com.wlyuan.open.validation.vaidators;

import cn.hutool.core.util.StrUtil;
import com.wlyuan.open.constants.SmsType;
import com.wlyuan.open.dto.OpenSmsCodeDTO;
import com.wlyuan.open.validation.constraints.SmsSend;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
public class SmsSendValidator implements ConstraintValidator<SmsSend, OpenSmsCodeDTO> {

    @Override
    public boolean isValid(OpenSmsCodeDTO smsCodeDTO, ConstraintValidatorContext constraintValidatorContext) {
        if (!Optional.ofNullable(smsCodeDTO).isPresent()) {
            constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("message", "参数不能为空");
            return false;
        }
        //绑定管理员账号，管理员账号不能为空
        if (SmsType.isBind(smsCodeDTO.getType()) && StrUtil.isBlank(smsCodeDTO.getAccount())) {
            constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("message", "管理员账号不能为空");
            return false;
        }
        //非绑定管理员，手机号不能为空
        if (!SmsType.isBind(smsCodeDTO.getType()) && StrUtil.isBlank(smsCodeDTO.getMobile())) {
            constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("message", "手机号不能为空");
            return false;
        }
        return true;
    }
}
